`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    13:57:35 03/31/2014 
// Design Name: 
// Module Name:    keyboard 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module keyboard( 
input wire clk, // Clock pin form keyboard 
input wire data, //Data pin form keyboard 
output reg [7:0] led, //Printing input data to led 
output [1:0] start_dir,
output start_u
); 
 reg [7:0] data_curr; 
 reg [7:0] data_pre; 
 reg [3:0] b; 
 reg flag; 
 
initial 
begin 
	b<=4'h1; 
	flag<=1'b0; 
	data_curr<=8'hf0; 
	data_pre<=8'hf0; 
	led<=8'hf0; 
end 
 
always @(negedge clk) //Activating at negative edge of clock from keyboard 
begin 
	case(b) 
		1:; //first bit 
		2:data_curr[0]<=data; 
		3:data_curr[1]<=data; 
		4:data_curr[2]<=data; 
		5:data_curr[3]<=data; 
		6:data_curr[4]<=data; 
		7:data_curr[5]<=data; 
		8:data_curr[6]<=data; 
		9:data_curr[7]<=data; 
		10:flag<=1'b1; //Parity bit 
		11:flag<=1'b0; //Ending bit 
	endcase 
	if(b<=10) 
	b<=b+1; 
	else if(b==11) 
	b<=1; 
end 
 
reg released;
always@(posedge flag)//release keyboard
begin 
 if(data_curr==8'hf0) released <= 1'b1; 
 else if(released!=1'b0) released <= 1'b0;
 else released <= released;
end

reg p1_l, p1_r, p1_u;

reg [1:0] p1_dir = 0;

always@(posedge flag)
begin
	if(released==1'b0)
	begin
		case(data_curr)
		8'h6B: 
			begin
			p1_l <= 1'b1;
			p1_dir <= 2'd1;
			end
		8'h74: 
			begin
			p1_r <= 1'b1;
			p1_dir <= 2'd2;
			end
		8'h75: p1_u <= 1'b1;
		default:
			begin
			p1_l <= p1_l;
			p1_r <= p1_r;
			p1_u <= p1_u;
			p1_dir <= p1_dir;
			end
		endcase
	end
	else
	begin
		case(data_curr)
		8'h6B: begin
				 p1_l <= 1'b0;
				 p1_dir <= (p1_r) ? 2'd2: 2'd0;
				 end
		8'h74: begin 
		       p1_r <= 1'b0;
				 p1_dir <= (p1_l) ? 2'd1: 2'd0;
				 end
		8'h75: p1_u <= 1'b0;
		default:
			begin
			p1_l <= p1_l;
			p1_r <= p1_r;
			p1_u <= p1_u;
			p1_dir <= p1_dir;
			end
		endcase
	end
end


//assign start_l = p1_l;
//assign start_r = p1_r;
assign start_dir = p1_dir;
assign start_u = p1_u;



endmodule
